<template>
  <div  class="app-container"  v-loading="loading">
    <div style="font-size: 14px;color: #9d9d9d;margin-left: 10px">
      功能描述：单个账号视频一键发布(暂时只支持视频号发布)
    </div>
    <div style="margin-top: 10px;">
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">

<!--        标签样式-->
        <div style="display: flex;margin-bottom: 30px;margin-top: 20px">
          <div style="width: 5px;height: 15px;background: #7983f3;border-radius: 5px;margin-top: 4px"></div>
          <div style="margin-left: 10px;color: #797979"><b>选择视频</b></div>
        </div>

        <!--        选择视频   -->
        <el-row :gutter="24">
          <el-col :span="16">
            <el-form-item label="视频文件" prop="filePath">
              <div ref="drag"  class="videoData" @click="selectDir(1)">
                <div v-if="!form.filePath">
                  <img style="height: 40px;height: 40px;margin-top: 20%" src="@/assets/images/video.png">
                  <div style="font-size: 17px;color: #949494">
                    点击或将mp4文件拖动到此处上传
                  </div>
                </div>
                <video
                  v-if="form.filePath"
                  id="my-video"
                  :controls="form.filePath !== undefined"
                  preload="auto"
                  width="500px"
                  height="300px"
                  :src="form.filePath"
                >
                </video>
              </div>
<!--              <el-input disabled placeholder="请选择mp4文件" style="width: 70%;" v-model="form.filePath"></el-input>-->
              <div v-if="form.filePath" style="display: flex">
                <el-button type="primary"  style="margin-left: 28%;margin-top: 20px" @click="selectDir(1)">
                  更换视频
                </el-button>
                <el-button type="danger"  style="margin-left: 20px;margin-top: 20px" @click="removeVideo">
                  删除视频
                </el-button>
              </div>
            </el-form-item>
          </el-col>
        </el-row>


        <!--        标签样式-->
        <div style="display: flex;margin-bottom: 30px;margin-top: 20px">
          <div style="width: 5px;height: 15px;background: #7983f3;border-radius: 5px;margin-top: 4px"></div>
          <div style="margin-left: 10px;color: #797979"><b>选择账号</b></div>
        </div>



        <el-row :gutter="24">
          <el-col :span="24">
            <el-form-item label="选择账号" prop="accountId">
              <el-button v-if="!currentRow.id" @click="selectAccount">
                选择账号
              </el-button>
              <div>
              </div>
              <el-button v-if="currentRow.id" @click="selectAccount">
                更换账号
              </el-button>
              <div v-if="currentRow.id" style="cursor:pointer;display: flex;margin-top: 30px">
                <el-tag  style="cursor:pointer;" >{{currentRow.nickname}}</el-tag>
                <el-tag v-if="currentRow.acctType === 1">管理员</el-tag>
                <el-tag type="success" v-if="currentRow.acctType === 2">运营者</el-tag>
                <img :src="currentRow.headImgUrl" style="width: 50px;height: 50px;border-radius: 50px;margin-left: 20px"/>
              </div>
            </el-form-item>
          </el-col>
        </el-row>

        <!--        标签样式-->
        <div style="display: flex;margin-bottom: 30px;margin-top: 10px">
          <div style="width: 5px;height: 15px;background: #7983f3;border-radius: 5px;margin-top: 4px"></div>
          <div style="margin-left: 10px;color: #797979"><b>发布配置</b></div>
        </div>


<!--        视频描述   -->
        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="视频描述" prop="description">
              <el-input type="textarea"  v-model="form.description" :rows="3" placeholder="请输入视频描述"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

<!--        视频扩展链接  -->
        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="扩展链接" prop="link">
              <el-input v-model="form.link" clearable placeholder="将公众号文章链接或红包封面链接粘贴在此处"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

<!--        短标题  -->
        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="短标题" prop="link">
              <el-input v-model="form.shortTitle"  clearable placeholder="概括视频主要内容，字数建议6-16个字符"></el-input>
            </el-form-item>
          </el-col>
        </el-row>



        <!--  为之后的账号设置延时秒数    -->
        <el-row :gutter="24">
          <el-col :span="12">
            <div  style="display: flex">
              <el-form-item label="延时时间" prop="outTime">
                <el-input type="number" style="width: 240px;"   v-model="form.outTime"  placeholder="默认延时5秒后上传下一个"></el-input>
              </el-form-item>
              <el-tooltip effect="dark" content="当该视频发布成功后为下一个视频延时发布，避免发布频繁被官方限制导致的发布失败。" placement="top">
                <i class="el-icon-question" style="margin-left: 10px"></i>
              </el-tooltip>
            </div>
          </el-col>
        </el-row>



<!--        发布类型  -->
        <el-row :gutter="24">
          <el-col :span="24">
            <el-form-item label="发布时间">
              <el-radio-group v-model="form.publishType">
                <el-radio label="1">立即发布</el-radio>
                <el-radio label="2">定时发布</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>

<!--        定时时间  -->
        <el-row :gutter="24" v-show="form.publishType === '2'">
          <el-col :span="24">
            <el-form-item label="定时时间" prop="publishTime">
              <el-date-picker
                v-model="form.publishTime"
                type="datetime"
                placeholder="选择发布时间"
                default-time="12:00:00">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>

<!--        是否原创类型   -->
        <el-row :gutter="24">
          <el-col :span="24">
            <el-form-item label="是否原创">
              <el-radio-group v-model="form.mode">
                <el-radio label="0">非原创</el-radio>
                <el-radio label="1" @change="showOriginalityDialog">原创</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>

    <!--   选择账号model  -->
    <el-dialog title="选择发布账号" :visible.sync="checkAccountVisable"  width="1100px" append-to-body>
      <div style="display: flex;">
        <div  style="width: 300px;display: flex;flex-direction: column">
<!--          <div style="margin-left: 100px;font-size: 17px;margin-bottom: 10px;color: #626262">账号分组</div>-->
          <group-select @getGroupData="getGroupData" @reloadData="resetQuery"></group-select>
        </div>

        <div style="width: 700px;">
      <el-form :model="queryParams" ref="queryForm" size="small" @submit.native.prevent :inline="true"  label-width="68px">
        <el-form-item label="账号昵称" prop="nickname">
          <el-input
            v-model="queryParams.nickname"
            placeholder="请输入账号昵称"
            clearable
            @keyup.enter.native="getList"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="getList">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <div style="color: #a1a1a1;font-size: 16px;margin: 20px">
        请选中需要发布的账号
      </div>

      <el-table v-loading="loading" :data="accountList"  height="480"   highlight-current-row  @current-change="handleSelectionChange"  >
        <!--          <el-table-column type="selection" width="55" align="center" />-->
        <!--          :row-class-name="rowStyle"-->
        <el-table-column label="账号头像" align="center" prop="headImgUrl" >
          <template slot-scope="scope">
            <img :src="scope.row.headImgUrl" style="width: 50px;height: 50px;border-radius: 50px">
          </template>
        </el-table-column>
        <el-table-column label="账号昵称" align="center" prop="nickname" >
          <template slot-scope="scope">
            <span style="font-size: 13px;color: #646464;">{{scope.row.nickname}}</span>
          </template>
        </el-table-column>
        <el-table-column label="账号类型" align="center" prop="acctType" >
          <template slot-scope="scope">
            <el-tag v-if="scope.row.acctType === 1">管理员</el-tag>
            <el-tag type="success" v-if="scope.row.acctType === 2">运营者</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="平台" align="center" prop="platform" >
          <template slot-scope="scope">
            <img :src="require('@/assets/media/' + scope.row.platformCode + '.png' )" style="width: 30px;height: 30px;border-radius: 50px">
          </template>
        </el-table-column>
        <!--                <el-table-column label="平台图标" align="center" prop="logo" /> -->
        <el-table-column label="账号登录状态" align="center" prop="loginStatus" >
          <template slot-scope="scope">
            <el-tag :type="scope.row.loginStatus === 1 ? '' : 'danger'"
                    style="cursor:pointer" >
              {{scope.row.loginStatus === 1 ? '已登录' : '已掉线'}}
            </el-tag>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
      </div>
      </div>

      <div slot="footer" class="dialog-footer">
        <el-button :loading="buttonLoading" type="primary" @click="checkAccountData">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <div style="position:absolute;bottom: 50px;right: 50px;">
      <el-button type="primary"  @click="submitForm">发布</el-button>
    </div>
  </div>
</template>
<script>
import groupSelect from '@/views/media/accountGroup/groupSelect/index'
import { listMediaAccount } from "@/api/media/mediaAccount";
import { publishVideo } from "@/api/media/channelsPublish";
import { Message } from "element-ui";
import { addPublishRecord} from "@/api/media/publishRecord";
import store from "@/store";
import { getToken } from "@/utils/auth";
export default {
  name: "videoPublish",
  components:{
    groupSelect
  },
  data() {
    return {
      buttonLoading:false,
      checkAccountVisable:false,
      percent: 50, // the percentage of the progress bar
      color: '#409EFF', // the color of the progress bar
      strokeWidth: 15, // the width of the progress bar stroke
      loading:false,
      total:0,
      accUser:[],
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      activeName:'one',
      checkAll: false,
      currentRow:{},
      form:{
        link:undefined,
        publishType:'1',
        description:undefined,
        accountId:undefined,
        publishTime:undefined,
        filePath: undefined,
        shortTitle:undefined,
        outTime:5,
        mode:'0'
      },
      dialogVisible:false,
      publishTime:'',
      rules:{
        accountId: [
          { required: true, message: "账号不能为空", trigger: "blur" }
        ],
        filePath:[
          { required: true, message: "视频文件不能为空", trigger: "blur" }
        ],
        publishTime:[
        { required: true, message: "发布时间不能为空", trigger: "blur" }
        ]
      },
      queryParams:{
        pageNum: 1,
        pageSize: 10,
        platformCode:'wxsph'
      },
      dir_path:'',
      isIndeterminate: true,
      accountList:[]
    };
  },
  created() {
    this.getList();
  },

  async mounted() {
    // 给容器绑定相关的拖拽事件
    this.bindEvents()
  },
  methods: {



    /**
     * 移除视频
     */
    removeVideo(){
      this.form.filePath = undefined
    },

    /**
     * 获取分组数据
     * @param item
     */
    getGroupData(item){
      console.log(item)
      this.queryParams.groupId = item.id
      this.getList()
    },



    bindEvents() {
      const drag = this.$refs.drag
      // 被拖动的对象进入目标容器
      drag.addEventListener('dragover', e => {
        e.preventDefault()
        drag.style.borderColor = '#5674d7'
      })
      // 被拖动的对象离开目标容器
      drag.addEventListener('dragleave', e => {
        e.preventDefault()
        drag.style.borderColor = '#d9d9d9'
      })
      // 被拖动的对象进入目标容器，释放鼠标键
      drag.addEventListener('drop', e => {
        e.preventDefault()
        drag.style.borderColor = '#d9d9d9'
        const fileList = e.dataTransfer.files
        let videoPath  = fileList[0].path;
        if(videoPath.indexOf(".mp4") === -1){
          Message.error("只能上传mp4格式的视频文件!")
          return;
        }
        this.form.filePath = videoPath;
      })
    },

    async uploadFile() {
      const form = new FormData()
      form.append('name', 'file')
      form.append('file', this.file)
      const res = await axios.post('/upload', form)
    },

    handleFileChange(e) {
      const file = e.target.files[0]
      console.log(file)
      // if (!file) return
      // this.file = file
      // this.uploadFile()
    },
    /**
     * 选择账号时弹框选择对应账号
     */
    selectAccount(){
      this.checkAccountVisable = true;
    },

    /**
     * 重置按钮
     */
    resetQuery(){
      this.queryParams = {}
        this.getList()
    },


    /**
     * 选中账号信息
     */
    checkAccountData(){
      if(this.currentRow.loginStatus === 0){
        Message.error("当前选中账号已掉线，请登录后操作！")
        return;
      }
      console.log(this.currentRow)
      this.checkAccountVisable = false;
      console.log(this.ids)
    },

    /**
     * 关闭表格弹框
     */
    cancel(){
      this.checkAccountVisable =  false
    },

    /** 查询账号管理列表 */
    getList() {
      this.loading = true;
      listMediaAccount(this.queryParams).then(response => {
        this.accountList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },

    /**
     * 选择是否原创发布
     */
    showOriginalityDialog(){
        this.$confirm('原创内容将受平台保护，盗用原创内容将受到平台处罚。', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.form.mode = '1';
        }).catch(() => {
          this.form.mode = '0';
        });
    },


    // 多选框选中数据
    handleSelectionChange(val) {
      if(val.loginStatus === 0){
        Message.error("当前选中账号已掉线，请登录后操作！")
        return;
      }
      this.currentRow = val;
      // this.checkAccountVisable = false;
    },


    /**
     * 选择文件夹
     */
    async selectDir(num) {
      const self = this;
      if(num === 1){
        const result =  await  this.serviceInvoke("controller.system.selectFolder",0) //文件上传
        // console.log(result[0])
        this.form.filePath = result[0]
      }else{
        const result =  await  this.serviceInvoke("controller.system.selectFolder",1)  //文件夹上传
        this.form.filePath = result[0]
      }
      // console.log(this.form.filePath)
    },

    // 表单重置
    reset() {
      this.form = {
        link:undefined,
        publishType:'1',
        description:undefined,
        accountId:undefined,
        publishTime:undefined,
        filePath: undefined,
        shortTitle:undefined,
        outTime:5,
        mode:'0'
      };
    },

    /**
     * 改变行样式
     * @param row
     * @param rowIndex
     */
    rowStyle({row, rowIndex}){
      if(this.currentRow.id === row.id){
        return 'checked'
      }else{
        return 'noChecked'
      }
    },



    /**
     * 发布视频
     */
    async  submitForm() {
      if (!this.currentRow.id) {
        Message.error("请选择账号！")
        return;
      }
      if (!this.form.filePath) {
        Message.error("请选择视频文件！")
        return;
      }
      if (this.form.publishType === '2' && !this.form.publishTime) {
        Message.error("请选择发布时间！")
        return;
      }
      console.log(this.currentRow)
      let args = {
        id:undefined,
        username:store.getters.name,  //添加队列用不到，发布接口需要
        accountId:this.currentRow.id,
        filePath:this.form.filePath,
        description:this.form.description,
        link:this.form.link,
        outTime:this.form.outTime,
        shortTitle:this.form.shortTitle,
        mode:this.form.mode,
        effectiveTime: this.form.publishTime ? Number(this.form.publishTime.getTime() / 1000) : undefined,
        cookies: this.currentRow.cookies,
        _log_finder_id: this.currentRow.finderUserName,
        _log_finder_uin: this.currentRow.ownerWxUin,
      }
      //先提交到任务队列中   添加队列的逻辑
       await addPublishRecord(args).then(async (res)=>{
         if(res.code === 200){
           //返回的主键赋值
           args.id = res.msg;
           await  this.serviceInvoke("controller.media.channels",args)
           Message.success("发布任务已提交，请在发布记录中查看！")
         }
       })
      // await  this.serviceInvoke("controller.media.channels",args)

      //重置参数
      this.reset();
    },


    convertCookies(cookies) {
      let cookieString = ''
      const Cookies = JSON.parse(cookies)
      for (let cookie of Cookies) {
        cookieString += `${cookie['name']}=${cookie['value']}; `
      }
      return cookieString
    },

    /**
     * 获取请求cookie
     * @param cookies
     * @returns {string}
     */
    resetCookie(cookies){
      let ResCookie = ''
      let jsonCookie = JSON.parse(cookies);
      for (let i = 0 ; i < jsonCookie.length;i++) {
        if(jsonCookie[i].name === 'sessionid'){
          ResCookie =  'sessionid=' + jsonCookie[i].value;
        }
      }
      return ResCookie;
    }




  }
};
</script>
<style lang="scss" scoped>

.el-table .checked {
  background: #051226 !important;
  cursor: pointer;
  transition: all .3s;
}

.el-table .noChecked {
  cursor: pointer;
  background: #fcfcfc !important;
}

.videoData{
  background: #f8f8f8;
  position: relative;
  width: 500px;
  height: 300px;
  border: 2px dotted #e7e7e7;
  border-radius: 10px;
  cursor:pointer;
  text-align: center
}


.drag {
  width: 660px;
  height: 300px;
  border: 2px dashed;
  border-color: #a3a3a3;
  border-radius: 5px;
  margin: 0 auto;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  flex-wrap: wrap;
.drag-icon-box {
  width: 100%;
  height: 60px;
  text-align: center;
  font-size: 50px;
  line-height: 60px;
  color: #606266;
}
.drag-message {
  width: 100%;
  height: 50px;
  line-height: 50px;
  text-align: center;
.drag-message-title {
  font-size: 14px;
  color: #606266;
}
.drag-message-label {
  width: 120px;
  height: 50px;
  height: auto;
  position: relative;
  overflow: hidden;
.drag-message-input {
  position: absolute;
  left: -100px;
  top: -100px;
  z-index: -1;
  display: none;
}
.drag-message-manual {
  font-size: 14px;
  color: #4b87ff;
  cursor: pointer;
}
}
}
}
</style>

